iT邦幫忙

2021 iThome 鐵人賽

DAY 24
0

Golang

測試

轉換一下心情,來嘗試看看單元測試好了

在golang上要跑測試的話,可以考慮先試看看內建 testing 套件。

首先,我們需要先import testing,之後跟很多單元測試雷同,我們需要讓function name做點變化,func TestXxx

大致上需要注意以下的幾個規則

  1. 檔名必須遵守xxx_test.go命名規則
  2. function必須是TestXxx開頭
  3. function參數必須 t *testing.T
  4. 執行檔案跟測試檔案必須是同一個package

先來看 The Go Playground的test 範例,原版是下面這樣

package main

import (
	"testing"
)

// LastIndex returns the index of the last instance of x in list, or
// -1 if x is not present. The loop condition has a fault that
// causes somes tests to fail. Change it to i >= 0 to see them pass.
func LastIndex(list []int, x int) int {
	for i := len(list) - 1; i > 0; i-- {
		if list[i] == x {
			return i
		}
	}
	return -1
}

func TestLastIndex(t *testing.T) {
	tests := []struct {
		list []int
		x    int
		want int
	}{
		{list: []int{1}, x: 1, want: 0},
		{list: []int{1, 1}, x: 1, want: 1},
		{list: []int{2, 1}, x: 2, want: 0},
		{list: []int{1, 2, 1, 1}, x: 2, want: 1},
		{list: []int{1, 1, 1, 2, 2, 1}, x: 3, want: -1},
		{list: []int{3, 1, 2, 2, 1, 1}, x: 3, want: 0},
	}
	for _, tt := range tests {
		if got := LastIndex(tt.list, tt.x); got != tt.want {
			t.Errorf("LastIndex(%v, %v) = %v, want %v", tt.list, tt.x, got, tt.want)
		}
	}
}

我們來改個版本看看

package main

import (
	"testing"
)

// LastIndex returns the index of the last instance of x in list, or
// -1 if x is not present. The loop condition has a fault that
// causes somes tests to fail. Change it to i >= 0 to see them pass.
func LastIndex(list []int, x int) int {
	for i := len(list) - 1; i > 0; i-- {
		if list[i] == x {
			return i
		}
	}
	return -1
}

func TestLastIndex(t *testing.T) {
	tests := []struct {
		list []int
		x    int
		want int
	}{
		{list: []int{1}, x: 1, want: -1},
		{list: []int{1, 1}, x: 1, want: 1},
		{list: []int{2, 1}, x: 2, want: -1},
		{list: []int{1, 2, 1, 1}, x: 2, want: 1},
		{list: []int{1, 1, 1, 2, 2, 1}, x: 3, want: -1},
		{list: []int{3, 1, 2, 2, 1, 1}, x: 3, want: -1},
	}
	for _, tt := range tests {
		if got := LastIndex(tt.list, tt.x); got != tt.want {
			t.Errorf("LastIndex(%v, %v) = %v, want %v", tt.list, tt.x, got, tt.want)
		}
	}
}

這樣跑我們就可以得到PASS,就是驗證都符合我們要的結果,那如果跑回原本的CASE,則會出現FAIL。

參考資料
https://pkg.go.dev/testing
https://play.golang.org/


上一篇
Golang 轉生到web世界 - gin Middleware中間件
下一篇
Validator 驗證
系列文
go go let's go - golang 從0開始30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言